package com.ruoyi.web.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.api.dto.ActivityDetailDto;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.master.domain.PmBusiness;
import com.ruoyi.master.service.IPmBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/business" )
public class MiniBusinessController {

    @Autowired
    private IPmBusinessService pmBusinessService;

    @Autowired
    private RedisCache redisCache;

    //获取热榜
    @GetMapping(value = "/getBusiness" )
    @ResponseBody
    public AjaxResult getMaxTimeActivityList() {

        try {
            List<PmBusiness> cacheList = redisCache.getCacheList(Constants.BUSINESS_KEY);
            if (cacheList.isEmpty()) {
                throw new RuntimeException();
            }
            return AjaxResult.success(cacheList);
        } catch (Exception e) {
            LambdaQueryWrapper<PmBusiness> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.orderByDesc(PmBusiness::getCreaterdate)
                    .last("limit 0 , 30");
            List<PmBusiness> businessList = pmBusinessService.list(queryWrapper);
            if (!businessList.isEmpty()) {
                businessList.forEach(pmBusiness -> {
                    pmBusiness.setPicture(Constants.IMG_PREFIX + pmBusiness.getPicture());
                });
            }
            redisCache.setCacheList(Constants.BUSINESS_KEY, businessList);
            return AjaxResult.success(businessList);
        }
    }

    /**
     * 根据活动ID获取赞助商详情
     */
    @GetMapping(value = "/businessDetail" )
    @ResponseBody
    public AjaxResult getBusinessDetailInfo(Long businessId) {

        List<PmBusiness> cacheList = redisCache.getCacheList(Constants.BUSINESS_KEY);
        LambdaQueryWrapper<PmBusiness> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PmBusiness::getId, businessId);
        PmBusiness business = pmBusinessService.getOne(queryWrapper);
        business.setPicture(Constants.IMG_PREFIX + business.getPicture());
        return AjaxResult.success(business);
    }

}
